package com.example.controller;

import com.example.entity.Goods;
import com.example.entity.GoodsCollectionDTO;
import com.example.entity.ShopCar;
import com.example.entity.User;
import com.example.service.GoodsService;
import com.example.service.ShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/cart")
public class ShopController {
    @Autowired
    private ShopService shopService;
    @Autowired
    private GoodsService goodsService;
    @RequestMapping("/list")
    public String list(HttpSession session, Model model){
        User user = (User) session.getAttribute("user");
        System.out.println(user);
        List<ShopCar> shopCar=shopService.FindGoodsByUid(user.getUid());
        System.out.println(shopCar);
        model.addAttribute("shopCar", shopCar);
        return "student/shopcar";
    }
    @RequestMapping("/add")
    public ModelAndView addCollection(@RequestParam int gid, HttpSession session) {
        User user = (User) session.getAttribute("user");
        Goods goods=goodsService.getGoodsById(gid);
        System.out.println(goods);
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        ModelAndView mv = new ModelAndView();
        if (user != null) {
            ShopCar shopCar=new ShopCar();
            shopCar.setGid(gid);
            shopCar.setUid(user.getUid());
            shopCar.setGname(goods.getGname());
            shopCar.setGprice(goods.getPrice());
            shopCar.setGtype(goods.getType());
            shopCar.setImg(goods.getImg());
            shopService.addshop(shopCar);
            shopService.FindGoodsByUid(user.getUid());
            List<ShopCar> shopCars=shopService.FindGoodsByUid(user.getUid());
            mv.setViewName("student/home");
            mv.addObject("shopCars", shopCars);
        }
        return mv;
    }
    @RequestMapping("/remove")
    public String remove(@RequestParam int shopid, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if(user == null) {
            return "redirect:/login";
        }

        shopService.remove(shopid);
        return "redirect:/cart/list";
    }
}
